import { reqGetUserInfo, reqLogin, reqGetUserInfoPhoto } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newtoken) {
    state.token = newtoken
    setToken(newtoken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removetoken(state) {
    state.token = null
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {

  async login(context, data) {
    const res = await reqLogin(data)
    console.log(res)
    const newtoken = res.data
    context.commit('setToken', newtoken)
  },
  async getUserInfo(context) {
    const { data: baseInfoObj } = await reqGetUserInfo()
    const { data: userphoto } = await reqGetUserInfoPhoto(baseInfoObj.userId)
    const allUserInfo = {
      ...baseInfoObj,
      ...userphoto
    }
    context.commit('setUserInfo', allUserInfo)
    return allUserInfo
  },
  logOut(context) {
    context.commit('removetoken')
    context.commit('removeUserInfo')
  }

}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
